﻿using System;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Xml.Linq;
using GalaSoft.MvvmLight.Messaging;

namespace Songhay.Wpf.WordWalkingStick.ViewModels
{
    using Extensions;
    using Songhay.Models;
    using Songhay.Office2010.Word;
    using Songhay.OpenXml;
    using Songhay.OpenXml.Models;
    using Songhay.Wpf.Mvvm;
    using Songhay.Wpf.Mvvm.ViewModels;
    using Songhay.Xml;

    /// <summary>
    /// View Model for the default Client
    /// </summary>
    public class ClientViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ClientViewModel"/> class.
        /// </summary>
        public ClientViewModel()
        {
            if(base.IsInDesignMode)
            {
                #region design-time data:

                this._flatOpcSourceString = ApplicationUtility
                    .LoadResource(new Uri("/Songhay.Wpf.WordWalkingStick;component/PackedFiles/FlatOpcToHtml.xml", UriKind.Relative));
                this._xhtmlSourceString = ApplicationUtility
                    .LoadResource(new Uri("/Songhay.Wpf.WordWalkingStick;component/PackedFiles/FlatOpcToHtml.html", UriKind.Relative));

                #endregion
            }
            else
            {
                #region runtime data:

                this._flatOpcSourceString = "Loading…";
                this._xhtmlSourceString = "Loading…";

                //Receive MvvmLight message:
                Messenger.Default.Register(this, new Action<GenericMessage<TransformationMessage>>(
                message =>
                {
                    var myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\WordWalkingStick\";
                    if(!Directory.Exists(myDocuments)) Directory.CreateDirectory(myDocuments);
                    var inputPath = myDocuments + "temp.docx";
                    var outputPath = myDocuments + "temp.html";

                    var flatOpcDoc = XDocument.Parse(message.Content.TransformationResult);
                    OpenXmlUtility.TransformFlatToOpc(flatOpcDoc, inputPath);

                    this.FlatOpcSourceString = flatOpcDoc.Root.ToString();

                    var settings = new SonghayHtmlConverterSettings()
                    {
                        PageTitle = "My Page Title " + DateTime.Now.ToString("U"),
                        UseEntityMap = false
                    };

                    OpenXmlUtility.WriteHtmlFile(inputPath, outputPath, settings);

                    var xhtmlDoc = XDocument.Load(outputPath);
                    this.XhtmlSourceString = xhtmlDoc.Root.ToString();
                }));

                #endregion

                base.BackgroundWorkerCommandDictionary.Add("CopyBody", new BackgroundWorkerUtilityData {
                    Input = new Action<object, DoWorkEventArgs>((o, args) =>
                    {
                        if(string.IsNullOrEmpty(this._xhtmlSourceString)) return;
                        var x = XDocument.Parse(this._xhtmlSourceString);
                        var body = x.Root.Element(XhtmlDocumentUtility.xhtml + "body");
                        if(body == null) return;
                        var text = body.GetInnerXml();
                        args.Result = text;
                    }),
                    Output = new Action<object, RunWorkerCompletedEventArgs>((o, args) =>
                    {
                        var text = (string)args.Result;
                        Clipboard.SetText(text);
                    })
                });
            }
        }

        /// <summary>
        /// Gets or sets the flat OPC source string.
        /// </summary>
        /// <value>The flat OPC source string.</value>
        public string FlatOpcSourceString
        {
            get
            {
                return _flatOpcSourceString;
            }
            set
            {
                _flatOpcSourceString = value;
                base.RaisePropertyChanged("FlatOpcSourceString");
            }
        }

        /// <summary>
        /// Gets or sets the XHTML source string.
        /// </summary>
        /// <value>The XHTML source string.</value>
        public string XhtmlSourceString
        {
            get
            {
                return _xhtmlSourceString;
            }
            set
            {
                _xhtmlSourceString = value;
                base.RaisePropertyChanged("XhtmlSourceString");
            }
        }

        string _flatOpcSourceString;
        string _xhtmlSourceString;
    }
}
